//
//  CZComposeTextView.swift
//  WeiBo
//
//  Created by Apple on 16/9/8.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

//  实时查看xib属性的变化效果
@IBDesignable
class CZComposeTextView: UITextView {

    // MARK:    --占位label
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.text = "听说下雨天音乐跟辣条更配哟"
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = UIColor.lightGray
        //  多行显示
        label.numberOfLines = 0
        
        return label
    }()
    
    
    //  占位字符串
    @IBInspectable var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    
    //  监听text的属性的变化，属性观察器
    override var text: String? {
        didSet {
            placeHolderLabel.isHidden = hasText
        }
    }
    
    //  监听font的属性的变化，属性观察器
    override var font: UIFont? {
        didSet {
            if font != nil {
                placeHolderLabel.font = font
            }
        }
    }
    
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        //  支持xib写法
        super.init(coder: aDecoder)
        setupUI()
    }
    
    //  添加控件设置约束
    private func setupUI() {
        
        //  监听文字改变的通知
       
       //   系统得通知，改成NSNotification.Name.系统得通知
        NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        addSubview(placeHolderLabel)
        //  使用代码布局
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        //  添加约束
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute:.leading , relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 8))
        //        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: -5))
        //        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .lessThanOrEqual, toItem: self, attribute: .width, multiplier: 1, constant: -10))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
        
    }
    
    @objc private func textChanged() {
        //  根据是否有文本，判断是否让其显示
        placeHolderLabel.isHidden = hasText
    }

    
}
